﻿using UnityEngine;

namespace FrameWorkSong
{
    public class AssetRes : Res
    {
        string my_Path;
        string my_OwnerBundleName;
        public AssetRes(string assetName, string ownerBundleName, string ownerBundelePath)
        {
            Name = assetName;
            my_OwnerBundleName = ownerBundleName;
            my_Path = ownerBundelePath;
        }
        ResLoader my_ResLoader = new ResLoader(); 

        public override void LoadAssetAsync()
        {
            State = ResState.Loading;
            my_ResLoader.LoadAssetAsync<AssetBundle>(my_OwnerBundleName, my_Path, ownerBundle =>
            {
                var assetBundleRequest = ownerBundle.LoadAssetAsync(Name);
                assetBundleRequest.completed += operation => 
                {
                    Asset = assetBundleRequest.asset;
                    State = ResState.Loaded;
                };
            });
        }

        public override bool LoadAssetSync()
        {
            State = ResState.Loading;
            var ownerBundle = my_ResLoader.LoadAssetSync<AssetBundle>(my_OwnerBundleName, my_Path);
            Asset = ownerBundle.LoadAsset(Name);
            State = ResState.Loaded;
            return Asset;
        }

        public override void ReleaseAsset()
        {
            if (Asset is GameObject)
            {
               
            }
            else
            {
                Resources.UnloadAsset(Asset);
            }
            my_ResLoader.Release(Name);
            Asset = null;
         
        }

        protected override void OnReleaseRes()
        {
            ReleaseAsset();
            ResMgr.Instance.ShareLoadedAssets.Remove(this);
            my_ResLoader.ReleaseAll();
            my_ResLoader = null;
        }
    }
}
